package cn.itcast.controller;

import cn.itcast.dao.Dept;
import cn.itcast.service.DeptService;
import cn.itcast.service.impl.DeptServiceImpl;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/controller/dept/*")
public class DeptServlet extends BaseServlet {
    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String page = req.getParameter("page");
        int pageNum = 1;
        if(page != null && !page.equals("")) {
            pageNum = Integer.parseInt(page);
        }


        DeptService deptService = new DeptServiceImpl();
        List<Dept> list = deptService.findAll(pageNum);
        PageInfo pageInfo = new PageInfo(list);
        req.setAttribute("page",pageInfo);
        req.getRequestDispatcher("/pages/store/dept/list.jsp").forward(req,resp);

    }

    public void findById(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        DeptService deptService = new DeptServiceImpl();
        Dept dept = deptService.findById(id);
        req.setAttribute("dept",dept);
        try {
            req.getRequestDispatcher("/pages/store/dept/update.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void edit(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException {
        Map<String, String[]> map = req.getParameterMap();
        Dept dept = new Dept();
        BeanUtils.populate(dept,map);
        DeptService deptService = new DeptServiceImpl();
        deptService.edit(dept);
        try {
            req.getRequestDispatcher("/controller/dept/findAll").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
